<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DeepSeek 智能助手</title>
    <link rel="stylesheet" href="https://cdn.staticfile.net/font-awesome/6.7.1/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.staticfile.net/tailwindcss/2.2.9/tailwind.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;500;600;700&family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <script src="https://cdn.staticfile.net/motion.js/0.3.0/motion.min.js"></script>
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4338CA',
                        secondary: '#10B981',
                        neutral: '#1F2937',
                        light: '#F3F4F6',
                        userBg: '#DBEAFE', // 淡蓝色背景
                        userText: '#4B5563', // 灰色文字
                        buttonBg: '#F97316', // 橙色按钮背景
                        buttonText: '#1F2937', // 按钮黑色文字
                    },
                    fontFamily: {
                        sans: ['Noto Sans SC', 'sans-serif'],
                        serif: ['Noto Serif SC', 'serif'],
                    },
                    boxShadow: {
                        'message': '0 2px 8px rgba(0, 0, 0, 0.08)',
                        'button': '0 2px 4px rgba(249, 115, 22, 0.3)', // 橙色按钮阴影
                    }
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .message-appear {
                animation: fadeIn 0.3s ease-out forwards;
            }
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(10px); }
                to { opacity: 1; transform: translateY(0); }
            }
            .pulse-animation {
                animation: pulse 2s infinite;
            }
            @keyframes pulse {
                0% { transform: scale(1); }
                50% { transform: scale(1.05); }
                100% { transform: scale(1); }
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans text-neutral min-h-screen flex flex-col">
    <!-- 顶部导航 -->
    <header class="bg-white shadow-md py-4 px-6 sticky top-0 z-50 transition-all duration-300">
        <div class="container mx-auto flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-comments text-primary text-2xl"></i>
                <h1 class="text-xl font-semibold text-neutral">DeepSeek 智能助手</h1>
            </div>
            <div class="flex items-center space-x-4">
                <button id="theme-toggle" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                    <i class="fa fa-moon-o text-neutral"></i>
                </button>
                <button id="settings-btn" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                    <i class="fa fa-cog text-neutral"></i>
                </button>
            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="flex-grow container mx-auto px-4 py-6 flex flex-col max-w-4xl">
        <!-- 聊天区域 -->
        <div id="chat-container" class="flex-grow overflow-y-auto scrollbar-hide mb-6 space-y-6 p-2">
            <!-- 欢迎消息 -->
            <div class="flex items-start message-appear">
                <div class="bg-primary text-white p-2 rounded-full mr-3 mt-1 shadow-md">
                    <i class="fa fa-robot"></i>
                </div>
                <div class="bg-white rounded-lg rounded-tl-none shadow-message p-4 max-w-[85%]">
                    <p class="text-neutral">你好！我是基于DeepSeek API的智能助手，有什么可以帮助你的吗？</p>
                    <p class="text-xs text-gray-500 mt-2">刚刚</p>
                </div>
            </div>
        </div>

        <!-- API设置模态框 -->
        <div id="settings-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
            <div class="bg-white rounded-lg shadow-xl p-6 w-full max-w-md transform transition-all scale-95 opacity-0" id="modal-content">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold">API 设置</h3>
                    <button id="close-settings" class="p-1 text-gray-500 hover:text-neutral rounded-full hover:bg-gray-100 transition-colors">
                        <i class="fa fa-times"></i>
                    </button>
                </div>
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">DeepSeek API Key</label>
                        <input type="password" id="api-key" placeholder="sk-..." 
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-buttonBg/50 transition-all">
                        <p class="text-xs text-gray-500 mt-1">请输入你的DeepSeek API密钥</p>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">系统提示词</label>
                        <textarea id="system-prompt" rows="3" 
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-buttonBg/50 transition-all"
                            placeholder="你是一个乐于助人的助手...">你是一个乐于助人的助手，能够回答各种问题并提供有用的信息。</textarea>
                    </div>
                    <!-- 保存设置按钮改为橙色背景黑色文字 -->
                    <button id="save-settings" class="w-full bg-buttonBg text-buttonText py-2 rounded-md hover:bg-buttonBg/90 transition-all shadow-button hover:shadow-lg transform hover:-translate-y-0.5 font-medium">
                        保存设置
                    </button>
                </div>
            </div>
        </div>

        <!-- 输入区域 -->
        <div class="bg-white rounded-lg shadow-md p-4 transition-all hover:shadow-lg">
            <form id="chat-form" class="flex flex-col space-y-3">
                <div class="relative">
                    <textarea id="user-input" rows="3" placeholder="输入你的消息..." 
                        class="w-full px-4 py-3 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-buttonBg/50 resize-none transition-all"></textarea>
                    <div class="absolute right-3 bottom-3 text-gray-400">
                        <span id="char-count">0</span>
                    </div>
                </div>
                <div class="flex justify-between items-center">
                    <div class="flex space-x-2">
                        <button type="button" class="p-2 text-gray-500 hover:text-buttonBg hover:bg-gray-100 rounded-full transition-all transform hover:scale-110">
                            <i class="fa fa-image"></i>
                        </button>
                        <button type="button" class="p-2 text-gray-500 hover:text-buttonBg hover:bg-gray-100 rounded-full transition-all transform hover:scale-110">
                            <i class="fa fa-file-text-o"></i>
                        </button>
                    </div>
                    <!-- 发送消息按钮改为橙色背景黑色文字 -->
                    <button type="submit" id="send-btn" class="bg-buttonBg text-buttonText px-6 py-3 rounded-lg hover:bg-buttonBg/90 transition-all shadow-button hover:shadow-lg font-medium flex items-center space-x-2 disabled:opacity-50 disabled:cursor-not-allowed transform hover:-translate-y-0.5">
                        <span>发送消息</span>
                        <i class="fa fa-paper-plane"></i>
                    </button>
                </div>
            </form>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-white py-4 px-6 border-t border-gray-200 mt-6">
        <div class="container mx-auto text-center text-gray-500 text-sm">
            <p>Powered by DeepSeek API | 使用 <i class="fa fa-heart text-red-500"></i> 制作</p>
        </div>
    </footer>

    <script>
        // DOM元素
        const chatForm = document.getElementById('chat-form');
        const userInput = document.getElementById('user-input');
        const chatContainer = document.getElementById('chat-container');
        const charCount = document.getElementById('char-count');
        const sendBtn = document.getElementById('send-btn');
        const settingsBtn = document.getElementById('settings-btn');
        const settingsModal = document.getElementById('settings-modal');
        const modalContent = document.getElementById('modal-content');
        const closeSettings = document.getElementById('close-settings');
        const saveSettings = document.getElementById('save-settings');
        const apiKeyInput = document.getElementById('api-key');
        const systemPromptInput = document.getElementById('system-prompt');
        const themeToggle = document.getElementById('theme-toggle');

        // 消息历史
        let messageHistory = [
            { role: "system", content: "你是一个乐于助人的助手，能够回答各种问题并提供有用的信息。" }
        ];

        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            // 加载保存的API设置
            const savedApiKey = localStorage.getItem('deepseekApiKey');
            const savedSystemPrompt = localStorage.getItem('systemPrompt');
            
            if (savedApiKey) {
                apiKeyInput.value = savedApiKey;
            }
            
            if (savedSystemPrompt) {
                systemPromptInput.value = savedSystemPrompt;
                messageHistory[0].content = savedSystemPrompt;
            }

            // 字符计数
            userInput.addEventListener('input', () => {
                charCount.textContent = userInput.value.length;
                sendBtn.disabled = userInput.value.trim() === '';
            });

            // 发送消息
            chatForm.addEventListener('submit', async (e) => {
                e.preventDefault();
                const message = userInput.value.trim();
                
                if (message) {
                    // 检查API密钥
                    if (!apiKeyInput.value.trim()) {
                        showError('请先在设置中配置你的DeepSeek API密钥');
                        return;
                    }

                    // 添加用户消息
                    addMessageToUI('user', message);
                    messageHistory.push({ role: 'user', content: message });
                    
                    // 清空输入框
                    userInput.value = '';
                    charCount.textContent = '0';
                    sendBtn.disabled = true;

                    // 获取AI回复
                    try {
                        await getAiResponse();
                    } catch (error) {
                        showError('获取回复失败: ' + error.message);
                    }
                }
            });

            // 设置模态框
            settingsBtn.addEventListener('click', () => {
                settingsModal.classList.remove('hidden');
                // 模态框动画
                setTimeout(() => {
                    modalContent.classList.remove('scale-95', 'opacity-0');
                    modalContent.classList.add('scale-100', 'opacity-100', 'transition-all', 'duration-300');
                }, 10);
            });

            closeSettings.addEventListener('click', closeSettingsModal);

            // 点击模态框外部关闭
            settingsModal.addEventListener('click', (e) => {
                if (e.target === settingsModal) {
                    closeSettingsModal();
                }
            });

            saveSettings.addEventListener('click', () => {
                const apiKey = apiKeyInput.value.trim();
                const systemPrompt = systemPromptInput.value.trim();
                
                if (apiKey) {
                    localStorage.setItem('deepseekApiKey', apiKey);
                }
                
                if (systemPrompt) {
                    localStorage.setItem('systemPrompt', systemPrompt);
                    messageHistory[0].content = systemPrompt;
                }
                
                closeSettingsModal();
                showSuccess('设置已保存');
            });

            // 主题切换
            themeToggle.addEventListener('click', () => {
                document.body.classList.toggle('dark-mode');
                const icon = themeToggle.querySelector('i');
                if (icon.classList.contains('fa-moon-o')) {
                    icon.classList.replace('fa-moon-o', 'fa-sun-o');
                    document.body.classList.add('bg-gray-900', 'text-white');
                    document.body.classList.remove('bg-gray-50', 'text-neutral');
                    document.querySelectorAll('header, footer, #chat-container > div > div:nth-child(2), #settings-modal > div, .bg-white').forEach(el => {
                        el.classList.add('bg-gray-800', 'text-white');
                        el.classList.remove('bg-white', 'text-neutral');
                    });
                } else {
                    icon.classList.replace('fa-sun-o', 'fa-moon-o');
                    document.body.classList.remove('bg-gray-900', 'text-white');
                    document.body.classList.add('bg-gray-50', 'text-neutral');
                    document.querySelectorAll('header, footer, #chat-container > div > div:nth-child(2), #settings-modal > div, .bg-gray-800').forEach(el => {
                        el.classList.remove('bg-gray-800', 'text-white');
                        el.classList.add('bg-white', 'text-neutral');
                    });
                }
            });
        });

        // 关闭设置模态框
        function closeSettingsModal() {
            modalContent.classList.remove('scale-100', 'opacity-100');
            modalContent.classList.add('scale-95', 'opacity-0', 'transition-all', 'duration-300');
            setTimeout(() => {
                settingsModal.classList.add('hidden');
            }, 300);
        }

        // 添加消息到UI - 用户消息使用淡蓝色背景和灰色文字
        function addMessageToUI(role, content) {
            const isUser = role === 'user';
            const now = new Date();
            const timeString = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
            
            const messageDiv = document.createElement('div');
            messageDiv.className = `flex items-start justify-${isUser ? 'end' : 'start'} message-appear`;
            
            messageDiv.innerHTML = `
                ${!isUser ? `
                <div class="bg-primary text-white p-2 rounded-full mr-3 mt-1 shadow-md">
                    <i class="fa fa-robot"></i>
                </div>
                ` : ''}
                <div class="bg-${isUser ? 'userBg' : 'white'} text-${isUser ? 'userText' : 'neutral'} rounded-lg ${!isUser ? 'rounded-tl-none' : 'rounded-tr-none'} shadow-message p-4 max-w-[85%] transition-all hover:shadow-lg">
                    <p>${formatMessage(content)}</p>
                    <p class="text-xs ${isUser ? 'text-gray-500' : 'text-gray-500'} mt-2">${timeString}</p>
                </div>
                ${isUser ? `
                <div class="bg-gray-200 text-neutral p-2 rounded-full ml-3 mt-1 shadow-sm">
                    <i class="fa fa-user"></i>
                </div>
                ` : ''}
            `;
            
            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        // 格式化消息（简单处理换行）
        function formatMessage(content) {
            return content.replace(/\n/g, '<br>');
        }

        // 获取AI回复
        async function getAiResponse() {
            // 添加加载指示器
            const loadingDiv = document.createElement('div');
            loadingDiv.className = 'flex items-start message-appear';
            loadingDiv.id = 'loading-indicator';
            loadingDiv.innerHTML = `
                <div class="bg-primary text-white p-2 rounded-full mr-3 mt-1 shadow-md">
                    <i class="fa fa-robot"></i>
                </div>
                <div class="bg-white text-neutral rounded-lg rounded-tl-none shadow-message p-4 max-w-[85%]">
                    <div class="flex space-x-1">
                        <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 0ms"></div>
                        <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 150ms"></div>
                        <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 300ms"></div>
                    </div>
                </div>
            `;
            chatContainer.appendChild(loadingDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;

            try {
                const response = await fetch('https://api.deepseek.com/chat/completions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${apiKeyInput.value.trim()}`
                    },
                    body: JSON.stringify({
                        model: 'deepseek-chat',
                        messages: messageHistory,
                        stream: false
                    })
                });

                // 移除加载指示器
                document.getElementById('loading-indicator').remove();

                if (!response.ok) {
                    const errorData = await response.json().catch(() => ({}));
                    throw new Error(errorData.error?.message || `HTTP错误: ${response.status}`);
                }

                const data = await response.json();
                const aiResponse = data.choices[0].message.content;
                
                // 添加AI回复到历史和UI
                messageHistory.push({ role: 'assistant', content: aiResponse });
                addMessageToUI('assistant', aiResponse);
                
            } catch (error) {
                // 移除加载指示器
                const loadingIndicator = document.getElementById('loading-indicator');
                if (loadingIndicator) loadingIndicator.remove();
                throw error;
            }
        }

        // 显示错误消息
        function showError(message) {
            addMessageToUI('assistant', `<span class="text-red-500">${message}</span>`);
        }

        // 显示成功消息
        function showSuccess(message) {
            const successDiv = document.createElement('div');
            successDiv.className = 'fixed top-4 right-4 bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg z-50 transform translate-y-0 opacity-100 transition-all duration-300';
            successDiv.textContent = message;
            document.body.appendChild(successDiv);
            
            setTimeout(() => {
                successDiv.classList.add('opacity-0', 'translate-y-[-20px]');
                setTimeout(() => successDiv.remove(), 300);
            }, 2000);
        }
    </script>
</body>
</html>
